﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TBR.Common;
using TBR.Entities;
using TBR.Entities.Message;

namespace TBR.Repositories
{
    public class DialogRepository
    {
        #region constructor
        public DialogRepository()
        {
            this.webhelper = new WebHelper();
            this.htmlhelper = new HtmlHelper();
            this.Messages = new List<Message>();
        }
        #endregion

        #region events
        public delegate void RequestEventHandler(object source, RequestEventArgs args);
        public class RequestEventArgs : EventArgs
        {
            public IList<Message> Messages;
            public bool IsSended;
        }
        #endregion

        #region SendMessagesCompleted
        public event RequestEventHandler SendMessagesCompleted;
        public void OnSendMessagesCompleted()
        {
            if (SendMessagesCompleted != null)
            {
                RequestEventArgs args = new RequestEventArgs();
                args.IsSended = this.IsSended;
                SendMessagesCompleted(this, args);
            }
        }

        private void webHelper_SendMessagesCompleted(object sender, TBR.Common.WebHelper.RequestEventArgs args)
        {
            webhelper.RequestCompleted -= webHelper_SendMessagesCompleted;
            IsSended = args.HtmlCode.IndexOf("Сообщение отправлено") != -1 ? true : false;
            OnSendMessagesCompleted();
        }
        #endregion

        #region GetDialogCompleted
        public event RequestEventHandler GetDialogCompleted;
        public void OnGetDialogCompleted()
        {
            if (GetDialogCompleted != null)
            {
                RequestEventArgs args = new RequestEventArgs();
                args.Messages = Messages;
                GetDialogCompleted(this, args);
            }
        }

        private void webHelper_GetDialogCompleted(object sender, TBR.Common.WebHelper.RequestEventArgs args)
        {
            if (args.HtmlCode.IndexOf("Удаление переписки") >= 0)
            {
                webhelper.RequestCompleted -= webHelper_GetDialogCompleted;
                List<string> strMessages = htmlhelper.GetDivCollections(args.HtmlCode, "Текст сообщения", "Удаление переписки", "</div>", "<div", HtmlHelper.Tag.Form).ToList();
                IList<Message> messagesOnCurrentPage = ExtractMessages(strMessages);
                bool isPagesEnded = Messages.Any(u =>
                {
                    foreach (var message in messagesOnCurrentPage)
                        if (message.Date == u.Date && message.TextMessage == u.TextMessage && message.Sender.Id == u.Sender.Id)
                            return true;
                    return false;
                });

                if (isPagesEnded)
                {
                    OnGetDialogCompleted();
                }
                else
                {
                    foreach (var message in messagesOnCurrentPage)
                        Messages.Add(message);
                    currentPage++;
                    GetDialog(ContactId, currentPage);
                }
            }
            else
            {
                Messages = null;
                OnGetDialogCompleted();
            }
        }
        #endregion

        #region properties
        private WebHelper webhelper { get; set; }
        private HtmlHelper htmlhelper { get; set; }
        private IList<Message> Messages { get; set; }
        private bool IsSended { get; set; }
        private int currentPage = 1;
        private int ContactId { get; set; }
        #endregion

        #region public methods
        public void SendMessage(int contactId, string messageText, string token)
        {
            webhelper.RequestCompleted += webHelper_SendMessagesCompleted;
            string sid = CookieHelper.GetPropertyCookieByKey("sid");
            Dictionary<string, string> dicPostParams = new Dictionary<string, string>();
            dicPostParams.Add("message", messageText);
            dicPostParams.Add("contact_id", contactId.ToString());
            dicPostParams.Add("token", token);
            webhelper.GetHtmlCode(new Uri(String.Format("http://tabor.ru/messages.php?sid={0}&contact_id={1}", sid, contactId.ToString())), WebHelper.Method.Post, dicPostParams);
        }

        public void GetDialog(int contactId, int page)
        {
            ContactId = contactId;
            webhelper.RequestCompleted += webHelper_GetDialogCompleted;
            string sid = CookieHelper.GetPropertyCookieByKey("sid");
            webhelper.GetHtmlCode(new Uri(String.Format("http://tabor.ru/messages.php?p={0}&sid={1}&contact_id={2}", page, sid, contactId.ToString())), WebHelper.Method.Get);
        }
        #endregion

        #region private methods
        private IList<Message> ExtractMessages(IList<string> strList)
        {
            var messages = new List<Message>();
            foreach (var div in strList)
            {
                var senderName = GetSenderName(div);
                var id = GetSenderId(div);
                var actionDate = GetActionDate(div);
                messages.Add(new Message
                {
                    Date = actionDate,
                    TextMessage = GetTextMessage(div),
                    IsRead = div.IndexOf("не прочитано") != -1 ? false : true,
                    Sender = new UserBase(id, senderName, actionDate, String.Empty)
                });
            }
            return messages;
        }

        private string GetSenderName(string text)
        {
            if (text.IndexOf("</a>") != -1)
            {
                text = text.Remove(text.IndexOf("</a>"));
                return text.Remove(0, text.LastIndexOf(">") + 1);
            }
            else
            {
                text = text.Remove(0, text.IndexOf("<b>") + 3);
                return text.Substring(0, text.IndexOf("</b>"));
            }
        }

        private string GetSenderId(string text)
        {
            if (text.IndexOf("</a>") != -1)
            {
                text = text.Remove(0, text.IndexOf("id=") + 3);
                return text.Substring(0, text.IndexOf("&amp"));
            }
            else return String.Empty;
        }

        private string GetActionDate(string text)
        {
            text = text.Remove(text.LastIndexOf("</span>"));
            return text.Remove(0, text.LastIndexOf(">") + 1);
        }

        private string GetTextMessage(string text)
        {
            text = text.Remove(text.IndexOf("</div>"));
            return text.Remove(0, text.LastIndexOf("<br/>") + 5);
        }

        #endregion
    }
}
